package com.lsh.ofc.worker.task;

import com.alibaba.fastjson.JSON;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.ofc.core.entity.*;
import com.lsh.ofc.core.enums.OfcTaskStatus;
import com.lsh.ofc.core.enums.OfcTaskType;
import com.lsh.ofc.core.enums.WGOrderType;
import com.lsh.ofc.core.exception.EC;
import com.lsh.ofc.core.proxy.service.WumartBasicService;
import com.lsh.ofc.core.service.OfcCustomerService;
import com.lsh.ofc.core.service.OfcObdService;
import com.lsh.ofc.core.service.OfcOrderService;
import com.lsh.ofc.core.service.OfcSoService;
import com.lsh.ofc.proxy.context.WumartBasicContext;
import com.lsh.ofc.proxy.model.CreateWgSoTransferReqDetail;
import com.lsh.ofc.proxy.model.CreateWgSoTransferReqHead;
import com.lsh.ofc.proxy.service.WgServiceProxy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * 创建SO任务
 *
 * @author huangdong
 * @date 16/9/5
 */
@Slf4j
@Component
public class OfcObd2SoJob extends AbstractOfcTaskJob {

    @Autowired
    private OfcOrderService ofcOrderService;

    @Autowired
    private OfcObdService ofcObdService;

    @Autowired
    private OfcSoService ofcSoService;

    @Autowired
    private WgServiceProxy wgServiceProxy;

    @Autowired
    private OfcCustomerService ofcCustomerService;

    @Autowired
    private WumartBasicService wumartBasicService;

    @Override
    protected OfcTaskType getFetchTaskType() {
        return OfcTaskType.OBD_SO_PSI;
    }

    @Override
    protected int processTask(OfcTask task) throws BusinessException {
        try {
            Long orderCode = task.getRefId();

            OfcOrderHead orderFilter = new OfcOrderHead();
            orderFilter.setOrderCode(orderCode);
            OfcOrderHead order = ofcOrderService.findOne(orderFilter, false);
            if (order == null) {
                log.info("订单不存在，订单号：{}", orderCode);
                return 0;
            }

            OfcObdHead filter = new OfcObdHead();
            filter.setOrderCode(orderCode);
            List<OfcObdHead> obdHeadList = ofcObdService.findList(filter, true);
            if (CollectionUtils.isEmpty(obdHeadList)) {
                log.info("so创建并过账-obd单不存在，订单号：{}", orderCode);
                return 0;
            }

            for (OfcObdHead obd : obdHeadList) {
                try {
                    Integer cusType = JSON.parseObject(obd.getExt()).getInteger(WumartBasicContext.CUSTYPE);
                    String customerId = this.wumartBasicService.getCostomerId(WumartBasicContext.buildContext(obd.getRegionCode(), obd.getSupplierCode(), obd.getSupplierOrg(), obd.getSupplierId(),obd.getSupplierGroup()));
                    String ownerId = this.wumartBasicService.getOwnerId(WumartBasicContext.buildContext(obd.getRegionCode(), obd.getSupplierCode(), obd.getSupplierOrg(), obd.getSupplierId(),obd.getSupplierGroup()));
                    String wgPath = this.wumartBasicService.getWmsPath(WumartBasicContext.buildContext(obd.getRegionCode(), obd.getSupplierCode(), obd.getSupplierOrg(), obd.getSupplierId(),obd.getSupplierGroup()));
                    OfcCustomer customer = this.ofcCustomerService.getCustomer(order.getAddressCode(), cusType, obd.getRegionCode());

                    List<OfcSoDetail> soDetailList = ofcSoService.findDtails(obd.getSoBillCode());
                    if (CollectionUtils.isEmpty(soDetailList)) {
                        return -1;
                    }

                    Map<String, OfcSoDetail> soDetailMap = new HashMap<>();
                    // TODO 需要优化 有隐患
                    for (OfcSoDetail soDetail : soDetailList) {
                        soDetailMap.put(soDetail.getSkuSupplyCode(), soDetail);
                    }

                    CreateWgSoTransferReqHead soTransferHead = this.buildWgSoTransferHead(Integer.valueOf(ownerId), Integer.valueOf(customerId), order, obd, customer, soDetailMap);
                    if (null == soTransferHead) {
                        return -1;
                    }
                    //调用so 过账接口
                    Boolean isSuccess = wgServiceProxy.sendSoAndTransfer(soTransferHead, wgPath);

                    if (!isSuccess) {
                        log.warn("请求进销存，创建SO并过账失败");
                        return -1;
                    }
                } catch (Exception e) {
                    log.error("请求进销存，创建SO并过账异常", e);
                    return -1;
                }
            }

            return 1;
        } catch (BusinessException e) {
            log.error("任务处理失败", e);
        }

        return -1;
    }

    /**
     * 构建请求头（请求进销存，创建SO并过账）
     *
     * @param ownerId
     * @param customerId
     * @param order
     * @param obd
     * @param ofcCustomer
     * @return
     */
    private CreateWgSoTransferReqHead buildWgSoTransferHead(Integer ownerId, Integer customerId, OfcOrderHead order, OfcObdHead obd, OfcCustomer ofcCustomer, Map<String, OfcSoDetail> soDetailMap) {
        CreateWgSoTransferReqHead reqHead = new CreateWgSoTransferReqHead();

        reqHead.setSource(1);
        reqHead.setOwnerId(ownerId);
        reqHead.setCustomerId(customerId + "");
        reqHead.setOrderId(obd.getSoBillCode());
        // 出库单号，发货并过帐；写sobillcode
        reqHead.setWarehouseOrderNo(obd.getSoBillCode());
        reqHead.setAddressInfo(order.getAddressInfo());
        reqHead.setWarehouseCode(obd.getWarehouseCode());
        reqHead.setOrderCustomerName(ofcCustomer.getCustName());
        // 对于进销存，不关心是否预售、非预售；因为都要出库，进行扣库存
        reqHead.setOrderType(String.valueOf(WGOrderType.SO.getCode()));
        reqHead.setOrderCustomerId(String.valueOf(ofcCustomer.getMpCustCode()));

        List<CreateWgSoTransferReqDetail> details = new ArrayList<>();
        int itemNo = 10;
        for (OfcObdDetail obdDetail : obd.getDetails()) {
            CreateWgSoTransferReqDetail detail = new CreateWgSoTransferReqDetail();

            OfcSoDetail soDetail = soDetailMap.get(obdDetail.getSkuSupplyCode());
            if (null == soDetail) {
                return null;
            }

            BigDecimal saleUnit = soDetail.getGoodsSaleUnit();
            BigDecimal goodsPrice = soDetail.getGoodsPrice();
            if (saleUnit.compareTo(BigDecimal.ZERO) > 0 && goodsPrice.compareTo(BigDecimal.ZERO) >= 0) {
                detail.setSalesPrice(goodsPrice.divide(saleUnit, 4, BigDecimal.ROUND_HALF_DOWN));
            } else {
                throw EC.ERROR.exception("【请求进销存，创建SO并过账】初始化文固so失败!!! 销售价格不合法 so bill code =" + obdDetail.getSoBillCode());
            }

            detail.setLineNo(itemNo + "");
            detail.setGoodsId(obdDetail.getSkuSupplyCode());
            detail.setQty(obdDetail.getSkuDeliverQty());
            detail.setExt(null);

            itemNo += 10;

            details.add(detail);
        }
        reqHead.setDetails(details);

        return reqHead;
    }

//    /**
//     * 构建行项目（请求进销存，创建SO并过账）
//     *
//     * @param obdDetail
//     * @return
//     */
//    private CreateWgSoTransferReqDetail buildWgSoTransferDetail(OfcObdDetail obdDetail) {
//        CreateWgSoTransferReqDetail detail = new CreateWgSoTransferReqDetail();
//
//        BigDecimal saleUnit = obdDetail.getGoodsSaleUnit();
//        BigDecimal goodsPrice = obdDetail.getGoodsPrice();
//        if (saleUnit.compareTo(BigDecimal.ZERO) > 0 && goodsPrice.compareTo(BigDecimal.ZERO) >= 0) {
//            detail.setSalesPrice(goodsPrice.divide(saleUnit, 4, BigDecimal.ROUND_HALF_DOWN));
//        } else {
//            throw EC.ERROR.exception("【请求进销存，创建SO并过账】初始化文固so失败!!! 销售价格不合法 so bill code =" + obdDetail.getSoBillCode());
//        }
//
//        detail.setLineNo(obdDetail.getItemNo()+ "");
//        detail.setGoodsId(obdDetail.getSkuSupplyCode());
//        detail.setQty(obdDetail.getSkuDeliverQty());
//        detail.setExt(null);
//
//        return detail;
//    }

    @Override
    protected boolean filterFlag(OfcTask task) {

        return false;
    }

    @Override
    protected List<OfcTask> fetchTasks(OfcTaskType type, Set<OfcTaskStatus> statuses, int shardingCount, List<Integer> shardingItems, int fetchSize) {
        return super.defaultFetchTasks(type, statuses, shardingCount, shardingItems, fetchSize);
    }

}
